package top.hmtools.captcha.controller;

import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import top.hmtools.captcha.cache.SimpleCahceHandle;
import top.hmtools.captcha.configuration.CaptchaAutoConfiguration;
import top.hmtools.captcha.greenbamboo.Captcha;
import top.hmtools.captcha.greenbamboo.CaptchaContext;
import top.hmtools.captcha.greenbamboo.ImageCode;
import top.hmtools.captcha.greenbamboo.styles.JCaptcha;

@Controller
public class CaptchaController {
	
	private final Logger logger = LoggerFactory.getLogger(CaptchaController.class);
	
	@Autowired
	private CaptchaAutoConfiguration captchaAutoConfiguration;

	/**
	 * 获取验证码图片
	 */
	@RequestMapping(value = "#{'${"+CaptchaAutoConfiguration.config_prefix+".uri:}'?:'/captcha/show'}",method=RequestMethod.GET)
	public void show() {
		// 生成 **验证码图像** 和对应 **字符串验证码**
		CaptchaContext cc = new CaptchaContext(JCaptcha.CODEER_NAME);
		// 获取验证码和字符串
		Captcha captcha = cc.getCaptcha();
		
		//设置生成规则
		cc.configCaptcha(this.captchaAutoConfiguration.getWidth(), captchaAutoConfiguration.getHeight(), captchaAutoConfiguration.getCodeLength());
		
		ImageCode imageCode = captcha.getImageCode();
		String code = imageCode.getCode();
		Image image = imageCode.getImage();
		
		if(this.logger.isDebugEnabled()){
			this.logger.debug("生成的验证码是：{}",code);
		}
		
		//放入session
		this.captchaAutoConfiguration.getSession().setAttribute(CaptchaAutoConfiguration.SESSION_CAPTCHA_KEY, code);
		this.captchaAutoConfiguration.getSession().setAttribute(CaptchaAutoConfiguration.SESSION_CAPTCHA_TIMESTAMP_KEY, System.currentTimeMillis());
		
		//写入一份到缓存
		String uuidParam = this.captchaAutoConfiguration.getRequest().getParameter(this.captchaAutoConfiguration.getUuidParamName());
		if(uuidParam != null && uuidParam.length()>0){
			SimpleCahceHandle.setAttribute(uuidParam, CaptchaAutoConfiguration.SESSION_CAPTCHA_KEY, code);
			SimpleCahceHandle.setAttribute(uuidParam, CaptchaAutoConfiguration.SESSION_CAPTCHA_TIMESTAMP_KEY, System.currentTimeMillis());
		}
		
		//输出图片到浏览器
		HttpServletResponse response = this.captchaAutoConfiguration.getResponse();
		ServletOutputStream outputStream = null;
		try {
			response.setContentType("image/png");
			response.setStatus(HttpServletResponse.SC_OK);
			outputStream = response.getOutputStream();
			ImageIO.write((RenderedImage)image, "png", outputStream);
		} catch (IOException e) {
			this.logger.error("传输验证码图片到浏览器失败："+e.getMessage(),e);
		}finally{
			if(outputStream!=null){
//				try {
//					outputStream.close();
//				} catch (IOException e) {
//				}
			}
		}
	}
}
